package com.chaos.framework.web.interceptor.handler;

import com.chaos.framework.web.annotation.WxminiLoginToken;
import com.chaos.framework.web.exception.AuthenticationException;
import com.chaos.framework.web.service.login.ILoginService;
import com.chaos.framework.model.dto.login.wxmini.WxMiniLoginUser;
import com.chaos.framework.model.dto.result.ResultEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

@Component
public class WxminiLoginHandler {

    @Qualifier("wxLoginService")
    @Autowired(required = false)
    ILoginService wxLoginService;

    public boolean handler(HttpServletRequest httpServletRequest, Method method) {
        WxminiLoginToken wxminiLoginToken = method.getAnnotation(WxminiLoginToken.class);
        if (wxminiLoginToken.required()) {
            if (wxLoginService == null) {
                return false;
            }
            String token = httpServletRequest.getHeader("token");
            WxMiniLoginUser loginUser = handleWxminiLogin(token, httpServletRequest);
            if (wxminiLoginToken.needPhone()) {
                if (StringUtils.isEmpty(loginUser.getPhone())) {
                    throw new AuthenticationException(ResultEnum.NEED_AUTHORIZE.getCode(), "需要授权手机号", httpServletRequest);
                }
            }
        }
        return true;
    }

    private WxMiniLoginUser handleWxminiLogin(String token, HttpServletRequest httpServletRequest) {
        // 执行认证
        if (StringUtils.isEmpty(token)) {
            throw new AuthenticationException(ResultEnum.LOGIN_AGAIN.getCode(), "无效Token，请重新登录", httpServletRequest);
        }
        WxMiniLoginUser loginUser = (WxMiniLoginUser) wxLoginService.getLoginUser(token);
        if (StringUtils.isEmpty(loginUser)) {
            throw new AuthenticationException(ResultEnum.LOGIN_AGAIN.getCode(), "登录过期，请重新登录", httpServletRequest);
        }
        return loginUser;
    }

}
